package com.qf.electronic.excel;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Calendar;

public class LocalDateConverter implements Converter<LocalDate> {

    //这个方法是将excel中读取的数据转换为LocalDate
    @Override
    public LocalDate convertToJavaData(ReadCellData<?> cellData,
                                           ExcelContentProperty contentProperty,
                                           GlobalConfiguration globalConfiguration) throws Exception {
        //解析出来的时间是当前系统时间距离1900年的天数
        int day = cellData.getNumberValue().intValue();
        //EasyExcel默认的日期开始时间是1900年
        LocalDate date = LocalDate.of(1900, 1, 1);
//        LocalDateTime time = LocalDateTime.of(1900, 1, 1, 0, 0);
//        return  time.plusDays(day - 2);
       return date.plusDays(day - 2);
    }

    //这个方法是将对象中的LocalDate转换至Excel
    @Override
    public WriteCellData<?> convertToExcelData(LocalDate value,
                                               ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) throws Exception {
//        Calendar c = Calendar.getInstance();
//        c.set(1900, Calendar.JANUARY, -1);
//        long t1 = c.getTimeInMillis();
//        c.set(value.getYear(), value.getMonthValue() - 1, value.getDayOfMonth());
//        long t2 = c.getTimeInMillis();
//        long days = (t2 - t1) / (24 * 60 * 60 * 1000);
//        BigDecimal decimal = new BigDecimal(days);
//        return new WriteCellData<>(decimal);
        int year = value.getYear();
        int month = value.getMonthValue();
        int day = value.getDayOfMonth();
        return new WriteCellData<>(year + "/" + month + "/" + day);
    }
}
